package com.linghu.example;



import okhttp3.*;
import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;

import java.io.IOException;
import java.util.Scanner;

/**
 * @author 令狐荣豪
 * @version 1.0
 */
public class OpenAIChat {
    public static void main(String[] args) throws IOException, JSONException {

        String url = "https://api.openai-hk.com/v1/chat/completions";

        OkHttpClient client = new OkHttpClient();

        MediaType mediaType = MediaType.parse("application/json");
        System.out.println("请输入问题：");
        Scanner scanner = new Scanner(System.in);
        String ques = scanner.next();

        String json = "{\n" +
                "  \"max_tokens\": 1200,\n" +
                "  \"model\": \"gpt-3.5-turbo\",\n" +
                "  \"temperature\": 0.8,\n" +
                "  \"top_p\": 1,\n" +
                "  \"presence_penalty\": 1,\n" +
                "  \"messages\": [\n" +
                "    {\n" +
                "      \"role\": \"system\",\n" +
                "      \"content\": \"You are ChatGPT, a large language model trained by OpenAI. Answer as concisely as possible.\"\n" +
                "    },\n" +
                "    {\n" +
                "      \"role\": \"user\",\n" +
                "      \"content\": \""+ques+"\"\n" +
                "    }\n" +
                "  ]\n" +
                "}";

        RequestBody body = RequestBody.create(mediaType, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer hk-i4k54d100000965311f30a6f3291cffc4d608b5ad6a29679")
                .build();

        Call call = client.newCall(request);
        Response response = call.execute();
        String result = response.body().string();

//        System.out.println(result);
        JSONObject jsonObject = new JSONObject(result);
        JSONArray choicesArray = jsonObject.getJSONArray("choices");
        JSONObject firstChoice = choicesArray.getJSONObject(0);
        JSONObject messageObject = firstChoice.getJSONObject("message");
        String content = messageObject.getString("content");

        System.out.println("Content: " + content);
    }

}
